﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SeizyUtils.Common.Utilities;

namespace SeizyUtils.Common.Data.Database.Parse
{
    class SetState : IParseState
    {
        private readonly StringBuilder setClause;

        public SetState()
        {
            setClause = new StringBuilder();
        }

        public IParseState ReadLine(string line, StringBuilder resultSql, QueryParam param)
        {
            if (line.StartsWith("[set end]"))
            {
                resultSql.Append("\n ");
                resultSql.Append(IgnoreQuotation(setClause.ToString()));
                return new ReadState();
            }

            //パラメータを置換する
            setClause.Append(QueryParser.replaceParam(line, param));

            return this;
        }

        /// <summary>
        /// SET句の先頭に「,」が存在する場合は、除外する
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private string IgnoreQuotation(string result)
        {
            if (setClause.Length == 0)
            {
                result = result.Trim();
                if (result.StartsWith(","))
                {
                    result = result.Substring(1);
                }
            }
            return result;
        }

    }
}
